package com.schedualnew.mq.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Week;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.schedualnew.mq.config.AppParamsConfig;
import com.schedualnew.mq.config.ApplyMQConfig;
import com.schedualnew.mq.constvalue.ActTypeConstValue;
import com.schedualnew.mq.constvalue.ExamStatusEnum;
import com.schedualnew.mq.dto.common.apply.ChangeExaminationStatusRequestVo2;
import com.schedualnew.mq.dto.esb.AccessControl;
import com.schedualnew.mq.dto.esb.ChangeExaminationStatusMsg;
import com.schedualnew.mq.dto.esb.MessageHeader;
import com.schedualnew.mq.dto.esb.dict.dept.NoticeDeptChangeMsg;
import com.schedualnew.mq.dto.esb.dict.exam.NoticeExamItemChangeMsg;
import com.schedualnew.mq.dto.esb.dict.user.NoticeUserChangeMsg;
import com.schedualnew.mq.dto.esb.mq.send.SendESBEntry;
import com.schedualnew.mq.dto.esb.mq.send.SendMsg;
import com.schedualnew.mq.dto.esb.mq.send.SendMsgInfo;
import com.schedualnew.mq.dto.exam.*;
import com.schedualnew.mq.dto.notice.NoticeRootDto;
import com.schedualnew.mq.entity.*;
import com.schedualnew.mq.entity.vo.ExamScheduleItemVo;
import com.schedualnew.mq.mapper.*;
import com.schedualnew.mq.util.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class CommonService {
    private static Logger logger = LoggerFactory.getLogger(CommonService.class);
    @Autowired
    private AppParamsConfig paramsConfig;
    @Autowired
    private MQClientService mqClientService;

    @Autowired
    private ExamScheduleItemMapper examScheduleItemMapper;

    @Autowired
    private ExamScheduleMapper examScheduleMapper;

    @Autowired
    private ExamScheduleApmMapper examScheduleApmMapper;

    @Autowired
    private ExamApplyMapper examApplyMapper;

    @Autowired
    private ExamApplyItemMapper examApplyItemMapper;

    @Autowired
    private ExamScheduleActMapper examScheduleActMapper;

    @Autowired
    private DictExamClassMapper dictExamClassMapper;

    @Autowired
    private DictDeptMapper dictDeptMapper;

    @Autowired
    private DictUsersMapper dictUsersMapper;

    @Autowired
    private DictExamItemMapper dictExamItemMapper;

    @Autowired
    private ApplyMQConfig applyMQConfig;

    @Autowired
    private DictExamQueueMapper dictExamQueueMapper;

    @Autowired
    private DictScheduleApmMapper dictScheduleApmMapper;

    @Autowired
    private DictScheduleApmRegularMapper dictScheduleApmRegularMapper;

    @Autowired
    private DictSysparamsMapper dictSysparamsMapper;

    @Autowired
    private ExamSysLogMapper examSysLogMapper;

    public boolean parseDetailMsg(Element element, Map<String, String> msgInfoMap) {
        Iterator<Element> it = element.elementIterator();

        while (it.hasNext()) {
            Element e = it.next();
            msgInfoMap.put(e.getName(), e.getText());
        }

        return true;
    }

    public String getMsgPattern(String fileName) {
        String msgPatternPath = FileUtils.getFilePath("msgPattern/" + fileName);
        if (StringUtils.isEmpty(msgPatternPath)) {
            logger.info("消息模板文件不存在");
            return null;
        }

        String msgPattern = FileUtils.readFromFile(msgPatternPath);
        if (StringUtils.isEmpty(msgPattern)) {
            logger.info("读取消息模板失败：" + msgPatternPath);
            return null;
        }

        return msgPattern;
    }


    /**
     * 构建返回值
     *
     * @param map
     * @param sign
     * @param desc
     */
    public void getCommonMap(Map<String, String> map, boolean sign, StringBuffer desc) {
        String patientSource = map.get("EXAM_PAT_RESOURCE_NAME");
        String esbOrderNoConf = "门诊=PS35004S04001,体检=PS35004S04002,住院=PS35004S04001,急诊=PS35004S04001";
        String orderNo = "PS35004S04001";
        if (!StringUtils.isEmpty(esbOrderNoConf)) {
            Map<String, Object> mapVs = DataTrans.StringToMap(esbOrderNoConf);
            orderNo = (String) mapVs.get(patientSource);
            map.put("ESB_ORDER_NO", orderNo);
        }
        String targetSysCodeConf = applyMQConfig.getTargetSysCode();
        String targetSysCode = "S01";
        if (!StringUtils.isEmpty(targetSysCodeConf)) {
            Map<String, Object> mapVs = DataTrans.StringToMap(targetSysCodeConf);
            targetSysCode = (String) mapVs.get(patientSource);
            map.put("TARGET_SYS_CODE", targetSysCode);
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("HH:mm:ss");
        map.put("CURR_DATE", dateFormat.format((new Date()).getTime()));
        map.put("CURR_TIME", dateFormat2.format((new Date()).getTime()));

        if (sign) {
            map.put("RESULT_CODE", "0");
            map.put("RESULT_DESC", "成功");
        } else {
            map.put("RESULT_CODE", "1");
            map.put("RESULT_DESC", desc.toString());
        }
    }


    /**
     * 通过监听到的消息改变数据库检查预约的状态
     *
     * @return
     */
    @Transactional
    public Boolean changeExamStatus(ChangeExaminationStatusMsg statusMsg) {
        logger.info("ChangeExaminationStatusMsg:{}", JSONUtil.toJsonStr(statusMsg));

        String applyNo = statusMsg.getELECTR_REQUISITION_NO();
        if (StringUtils.isBlank(applyNo) || StringUtils.isEmpty(applyNo)) {
            logger.error("申请单参数错误:申请单号为空");
            return false;
        }

        QueryWrapper<ExamApply> applyQueryWrapper = new QueryWrapper<>();
        applyQueryWrapper.eq("APPLY_NO", applyNo);
        ExamApply examApply = examApplyMapper.selectOne(applyQueryWrapper);

        if (Objects.isNull(examApply)) {
            logger.error("没有找到申请单信息:{}", JSONUtil.toJsonStr(statusMsg));
            return false;
        }
        String statusCode = statusMsg.getREQUISITION_STATUS_CODE();

        QueryWrapper<ExamApplyItem> applyItemQueryWrapper = new QueryWrapper<>();
        applyItemQueryWrapper.eq("APPLY_NO", applyNo);
        List<ExamApplyItem> examApplyItems = examApplyItemMapper.selectList(applyItemQueryWrapper);

        // 查询预约信息
        QueryWrapper<ExamScheduleItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("APPLY_NO", applyNo);
        List<ExamScheduleItem> examScheduleItems = examScheduleItemMapper.selectList(queryWrapper);

        List<String> signStataus = Arrays.asList(ExamStatusEnum.SCHEDULED.getHisStatusCode(), ExamStatusEnum.CREATE.getHisStatusCode());
        List<String> refundStatus = Arrays.asList(ExamStatusEnum.REVOCATION.getHisStatusCode(), ExamStatusEnum.REVOCATION2.getHisStatusCode(),
                ExamStatusEnum.REFUND.getHisStatusCode());
        // 没有预约记录且不是预约或者签到，且不是退费或者取消预约的
        // 自动加一条预约记录进行状态改变
        if (CollectionUtils.isEmpty(examScheduleItems)
                && (!signStataus.contains(statusCode)) && (!refundStatus.contains(statusCode))) {
            ExamApplyItem applyItem = examApplyItems.get(0);
            // 生成id
            String scheduledId = PKGeneratorSingle.getInstance().nextPKStr();
            // 插入预约信息
            ExamScheduleItem scheduleItem = new ExamScheduleItem();
            scheduleItem.setApplyNo(examApply.getApplyNo());
            scheduleItem.setScheduledId(scheduledId);
            scheduleItem.setItemNo(applyItem.getItemNo());
            scheduleItem.setItemName(applyItem.getItemName());

            ExamSchedule examSchedule = new ExamSchedule();
            examSchedule.setScheduledId(scheduledId);
            examSchedule.setApplyNo(applyNo);
            examSchedule.setScheduler("admin");
            examSchedule.setExamStatus("10");
            examSchedule.setScheduleStatus("08");
            examSchedule.setSchePath("01");
            examSchedule.setQueueClass("普通");
            examSchedule.setHospitalCode(examApply.getHospitalCode());

            examScheduleItemMapper.insert(scheduleItem);
            examScheduleMapper.insert(examSchedule);
        }
        examScheduleItems = examScheduleItemMapper.selectList(queryWrapper);

        /**
         * 撤销登记 我们这边需要给他取消报到状态，恢复到未预约状态 取消预约、退号
         */
        if (refundStatus.contains(statusCode)) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("APPLY_NO", applyNo);
            List<ExamScheduleItem> scheduleItems = examScheduleItemMapper.selectList(queryWrapper);
            // 不是合单才取消预约，合单就不取消预约
            if (CollectionUtils.isNotEmpty(scheduleItems) && scheduleItems.size() == 1) {
                // 退费和撤销登记都要取消预约
                cancelScheduleApm(examScheduleItems, examApply, examApplyItems);
            }
            // 推送取消预约的消息
            try {
                ChangeExaminationStatusRequestVo2 vo2 = new ChangeExaminationStatusRequestVo2();
                vo2.setApplyNo(applyNo);
                // 取消预约
                vo2.setActType("2");
                vo2.setStaffNo("admin");
                pushStatusMsg(vo2);
            } catch (Exception e) {
                logger.error("取消预约消息推送失败:", e);
            }
            try {
                // 如果是 退费 还需要将检查申请单作废
                if (ExamStatusEnum.REFUND.getHisStatusCode().equals(statusCode)) {
                    deleteApply(applyNo);
                }
            } catch (Exception e) {
                logger.error("作废申请单回写失败:", e);
            }
        }
        // 监听 pacs 系统的 已预约的记录
        else if (signStataus.contains(statusCode)) {
            ExamApplyItem applyItem = examApplyItems.get(0);
            if (Objects.isNull(applyItem)) {
                logger.error("监听PACS系统直接预约的预约状态失败!" + applyNo);
                return false;
            }
            // 生成id
            String scheduledId = PKGeneratorSingle.getInstance().nextPKStr();
            // 插入预约信息
            ExamScheduleItem scheduleItem = new ExamScheduleItem();
            scheduleItem.setApplyNo(examApply.getApplyNo());
            scheduleItem.setScheduledId(scheduledId);
            scheduleItem.setItemNo(applyItem.getItemCode());
            scheduleItem.setItemName(applyItem.getItemName());

            ExamSchedule examSchedule = new ExamSchedule();
            examSchedule.setScheduledId(scheduledId);
            examSchedule.setApplyNo(applyNo);
            examSchedule.setScheduler("admin");
            examSchedule.setExamStatus("10");
            examSchedule.setScheduleStatus("08");
            examSchedule.setSchePath("01");
            examSchedule.setQueueClass("普通");
            examSchedule.setHospitalCode(examApply.getHospitalCode());

            examScheduleItemMapper.insert(scheduleItem);
            examScheduleMapper.insert(examSchedule);
        } else {
            ExamStatusEnum type = ExamStatusEnum.getByStatusCode(statusCode);
            if (!CollectionUtils.isEmpty(examScheduleItems) && Objects.nonNull(type)) {
                for (ExamScheduleItem examScheduleItem : examScheduleItems) {
                    UpdateWrapper<ExamScheduleItem> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("EXAM_STATUS", type.getSourceType());
                    updateWrapper.eq("APPLY_NO", examScheduleItem.getApplyNo());

                    examScheduleItemMapper.update(null, updateWrapper);
                }
            } else {
                logger.error("没有找到预约信息不需要改变状态:{}", JSONUtil.toJsonStr(statusMsg));
                return false;
            }
        }
        return true;
    }


    /**
     * 取消预约
     * DELETE FROM EXAM_SCHEDULE_ITEM WHERE ITEM_NO = ? AND SCHEDULED_ID = ? AND APPLY_NO = ?
     * --
     * DELETE FROM EXAM_SCHEDULE WHERE SCHEDULED_ID = ?
     * -- 恢复数量
     * UPDATE EXAM_SCHEDULE_APM SET SCHEDULE_DATE=?, APM_CODE=?, COUNT=?, ORGANS=? WHERE SCHEDULE_DATE = ? AND APM_CODE = ?
     *
     * @return
     */
    public synchronized Boolean cancelScheduleApm(List<ExamScheduleItem> examScheduleItems, ExamApply examApply, List<ExamApplyItem> examApplyItems) {
        String applyNo = examApply.getApplyNo();

        if (CollectionUtils.isNotEmpty(examScheduleItems)) {
            for (ExamScheduleItem scheduleItem : examScheduleItems) {
                Map<String, Object> map = new HashMap<>();
                map.put("SCHEDULED_ID", scheduleItem.getScheduledId());
                map.put("APPLY_NO", applyNo);
                examScheduleItemMapper.deleteByMap(map);

                QueryWrapper<ExamSchedule> examScheduleQueryWrapper = new QueryWrapper<>();
                examScheduleQueryWrapper.eq("SCHEDULED_ID", scheduleItem.getScheduledId());
                ExamSchedule examSchedule = examScheduleMapper.selectOne(examScheduleQueryWrapper);

                if (Objects.nonNull(examSchedule)) {
                    map = new HashMap<>();
                    map.put("SCHEDULED_ID", scheduleItem.getScheduledId());
                    examScheduleMapper.deleteByMap(map);

                    if (StringUtils.isNotBlank(examSchedule.getApmCode()) && !"无".equals(examSchedule.getApmCode())) {
                        // 还原占用数量
                        // 恢复数量
                        // UPDATE EXAM_SCHEDULE_APM SET SCHEDULE_DATE=?, APM_CODE=?, COUNT=?, ORGANS=? WHERE SCHEDULE_DATE = ? AND APM_CODE = ?
                        QueryWrapper<ExamScheduleApm> scheduleApmQueryWrapper = new QueryWrapper<>();
                        scheduleApmQueryWrapper.eq(ExamScheduleApm.APM_CODE, examSchedule.getApmCode());
                        scheduleApmQueryWrapper.eq(ExamScheduleApm.SCHEDULE_DATE, examSchedule.getScheduledDate());

                        ExamScheduleApm scheduleApm = examScheduleApmMapper.selectOne(scheduleApmQueryWrapper);
                        Map<String, Object> updateMap = new HashMap<>();
                        updateMap.put("SCHEDULE_DATE", scheduleApm.getScheduleDate());
                        updateMap.put("APM_CODE", scheduleApm.getApmCode());
                        // 取消默认-1
                        double count = -1.0;
                        double organs = 0.0;
                        if (StringUtils.isNotBlank(examSchedule.getNextApmRatio())) {
                            count = Double.parseDouble(examSchedule.getNextApmRatio());
                        }
                        if (StringUtils.isNotBlank(examSchedule.getOrgans())) {
                            try {
                                organs = Double.parseDouble(examSchedule.getOrgans());
                            } catch (NumberFormatException ignored) {
                            }
                        }
                        updateMap.put("COUNT", count);
                        updateMap.put("ORGANS", organs);

                        examScheduleApmMapper.updateCountByMap(updateMap);
                    }
                } else {
                    logger.error("cancelScheduleApm:没有找到申请单号:{},{}", applyNo, JSONUtil.toJsonStr(examSchedule));
                }
                // 记录操作日志
                addExamScheduleAct(examApply, ActTypeConstValue.CANCEL, examApplyItems, examSchedule);
            }

        }
        return true;
    }

    /**
     * 作废申请单
     *
     * @param applyNo
     * @return
     */
    public synchronized Boolean deleteApply(String applyNo) {
        UpdateWrapper<ExamApply> applyUpdateWrapper = new UpdateWrapper<>();

        applyUpdateWrapper.set("APPLY_STATUS", "00");
        applyUpdateWrapper.eq("APPLY_NO", applyNo);
        examApplyMapper.update(null, applyUpdateWrapper);

        UpdateWrapper<ExamApplyItem> examApplyItemUpdateWrapper = new UpdateWrapper<>();
        examApplyItemUpdateWrapper.set("EXAM_STATUS", "00");
        examApplyItemUpdateWrapper.eq("APPLY_NO", applyNo);
        examApplyItemMapper.update(null, examApplyItemUpdateWrapper);

        ExamSysLog examSysLog = new ExamSysLog();
        examSysLog.setDescription("退费 删除exam_apply、exam_apply_item表记录");
        examSysLog.setOperateName("删除申请单");
        examSysLog.setModuleName("申请单接口");
        examSysLog.setExamNo(applyNo);
        examSysLogMapper.addSysLog(examSysLog);

        return true;

    }


    /***
     * 添加操作日志
     * @param examApply
     * @param actType
     * @param examApplyItem
     * @param examSchedule
     */
    public void addExamScheduleAct(ExamApply examApply, ActTypeConstValue actType, List<ExamApplyItem> examApplyItem, ExamSchedule examSchedule) {
        try {
            ExamScheduleAct act = new ExamScheduleAct();
            act.setApplyNo(examApply.getApplyNo());
            act.setActType(actType.getActType());
            act.setScheduleDate(examSchedule.getScheduledDate());
            act.setScheduleApm(examSchedule.getScheduleApm());
            act.setQueueName(examSchedule.getQueueName());
            act.setHospitalCode(examSchedule.getHospitalCode());
//        String userType = ConstantsUtil.UserType.DOCTOR.getType();
//        act.setUserType(userType);
//        act.setUserId(dictUsers.getUserId());
            act.setUserName("pacs");
//        act.setComputerName(dictUsers.getIpAddress());
            act.setTerminalType("P");// PACS
            String dateStr = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            String[] dateArr = dateStr.split(" ");
            act.setActDate(dateArr[0]);
            act.setActTime(dateArr[1]);
            act.setScheduledId(examSchedule.getScheduledId());
            String actDescription = actType.getDescStatus();
            if (StringUtils.isBlank(actDescription)) {
                StringBuffer bf = new StringBuffer();
                if (StringUtils.isNotBlank(examApply.getName())) {
                    bf.append(examApply.getName() + ",");
                }
                if (StringUtils.isNotBlank(examApply.getSex())) {
                    bf.append(examApply.getSex() + ",");
                }
                if (StringUtils.isNotBlank(examApply.getAge())) {
                    bf.append(examApply.getAge() + ",");
                }
                if (StringUtils.isNotBlank(examApply.getSickId())) {
                    bf.append("ID:" + examApply.getSickId() + ",");
                }
                if (StringUtils.isNotBlank(examSchedule.getScheduledId())) {
                    bf.append("预约ID:" + examSchedule.getScheduledId() + ",");
                }
                if (StringUtils.isNotBlank(examApply.getExamClass())) {
                    bf.append("检查类别:" + examApply.getExamClass() + ",");
                }
                if (!CollectionUtils.isEmpty(examApplyItem)) {
                    for (ExamApplyItem item : examApplyItem) {
                        bf.append(",申请单号:" + item.getApplyNo() + ",项目序号:" + item.getItemNo() + ",项目名称:" + item.getItemName());
                    }
                }
                actDescription = bf.toString();
            }
            act.setActDescription(actDescription);
            examScheduleActMapper.insert(act);
        } catch (Exception e) {
            logger.error("插入操作日志失败:", e);
        }
    }

    /**
     * 创建或者保存检查项目
     */
    @Transactional
    public void createOrUpdateExamItem(List<NoticeExamItemChangeMsg> msgs, String hospitalCode) {
        if (!CollectionUtils.isEmpty(msgs)) {
            for (NoticeExamItemChangeMsg msg : msgs) {
                QueryWrapper<DictExamItem> deptQueryWrapper = new QueryWrapper<>();
                deptQueryWrapper.eq("ITEM_CODE", msg.getExamItemCode());
                DictExamItem examItem = dictExamItemMapper.selectOne(deptQueryWrapper);
                if (Objects.nonNull(examItem)) {
                    // 更新
                    UpdateWrapper<DictExamItem> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("ITEM_CODE", msg.getExamItemCode());

                    if (StringUtils.isNotBlank(msg.getExamItemName())) {
                        updateWrapper.set("ITEM_NAME", msg.getExamItemName());
                    }
                    if (StringUtils.isNotBlank(msg.getExamClass())) {
                        updateWrapper.set("EXAM_CLASS", msg.getExamClass());
                    }
                    if (StringUtils.isNotBlank(msg.getExamSubClass())) {
                        updateWrapper.set("EXAM_SUB_CLASS", msg.getExamSubClass());
                    }
                    if (StringUtils.isNotBlank(msg.getNote())) {
                        updateWrapper.set("NOTICE", msg.getNote());
                    }

                    dictExamItemMapper.update(null, updateWrapper);
                } else {
                    DictExamItem item = new DictExamItem();
                    item.setItemCode(msg.getExamItemCode());
                    item.setItemName(msg.getExamItemName());
                    item.setExamClass(msg.getExamClass());
                    item.setExamSubClass(msg.getExamSubClass());
                    item.setNotice(msg.getNote());
                    // 插入
                    dictExamItemMapper.save(item);
                }

                QueryWrapper<DictExamClass> dictExamClassQueryWrapper = new QueryWrapper<>();
                dictExamClassQueryWrapper.eq("EXAM_CLASS_NAME", msg.getExamClass());
                DictExamClass dictExamClass = dictExamClassMapper.selectOne(dictExamClassQueryWrapper);
                if (Objects.isNull(dictExamClass)) {
                    // 插入新的
                    DictExamClass examClass = new DictExamClass();
                    examClass.setExamClassName(msg.getExamClass());
                    examClass.setExamClassCode(msg.getExamClass());
                    examClass.setCommonName(msg.getExamClass());
                    examClass.setHospitalCode(hospitalCode);
                    dictExamClassMapper.insert(examClass);
                }
            }
        }
    }

    /**
     * 创建或者保存检查项目
     */
    @Transactional(rollbackFor = {Exception.class})
    public void createOrUpdateDeptInfo(List<NoticeDeptChangeMsg> msgs, String hospitalCode) {
        if (!CollectionUtils.isEmpty(msgs)) {
            for (NoticeDeptChangeMsg msg : msgs) {
                QueryWrapper<DictDept> deptQueryWrapper = new QueryWrapper<>();
                deptQueryWrapper.eq("DEPT_CODE", msg.getDeptCode());

                DictDept dictDept = dictDeptMapper.selectOne(deptQueryWrapper);
                if (Objects.nonNull(dictDept)) {
                    UpdateWrapper<DictDept> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("DEPT_CODE", msg.getDeptCode());

                    if (StringUtils.isNotBlank(msg.getDeptName())) {
                        dictDept.setDeptName(msg.getDeptName());
                    }
                    if (StringUtils.isNotBlank(msg.getInputCode())) {
                        dictDept.setInputCode(msg.getInputCode());
                    }
                    if (StringUtils.isNotBlank(msg.getLocation())) {
                        dictDept.setLocation(msg.getLocation());
                    }

                    // 更新
                    dictDeptMapper.update(null, updateWrapper);
                } else {
                    // 插入
                    DictDept dept = new DictDept();
                    dept.setHospitalCode(hospitalCode);
                    dept.setDeptName(msg.getDeptName());
                    dept.setDeptCode(msg.getDeptCode());
                    dept.setLocation(msg.getDescr());
                    dept.setInputCode(msg.getInputCode());
                    dept.setLocation(msg.getLocation());

                    Integer sortNo = 0;
                    if (StringUtils.isNotBlank(msg.getDeptIndexNo())) {
                        sortNo = Integer.valueOf(msg.getDeptIndexNo());
                    }
                    dept.setSortNo(sortNo);
                    dictDeptMapper.insert(dept);
                }
            }
        }
    }


    /**
     * 创建或者保存检查项目
     */
    @Transactional(rollbackFor = {Exception.class})
    public void createOrUpdateUserInfo(List<NoticeUserChangeMsg> msgs, String hospitalCode) {
        if (!CollectionUtils.isEmpty(msgs)) {
            for (NoticeUserChangeMsg msg : msgs) {
                QueryWrapper<DictUsers> usersQueryWrapper = new QueryWrapper<>();
                usersQueryWrapper.eq("STAFF_NO", msg.getStaffCode());
                DictUsers dictUsers = dictUsersMapper.selectOne(usersQueryWrapper);

                if (Objects.nonNull(dictUsers)) {
                    UpdateWrapper<DictUsers> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("STAFF_NO", msg.getStaffCode());

                    if (StringUtils.isNotBlank(msg.getPassword())) {
                        dictUsers.setPassword(msg.getPassword());
                    }
                    if (StringUtils.isNotBlank(msg.getName())) {
                        dictUsers.setName(msg.getName());
                    }
                    if (StringUtils.isNotBlank(msg.getUserId())) {
                        dictUsers.setUserId(msg.getUserId());
                    }
                    if (StringUtils.isNotBlank(msg.getIntroduce())) {
                        dictUsers.setIntroduce(msg.getIntroduce());
                    }
                    if (StringUtils.isNotBlank(msg.getDeptCode())) {
                        dictUsers.setDeptCode(msg.getDeptCode());
                    }
                    // 更新
                    dictUsersMapper.update(dictUsers, updateWrapper);
                } else {
                    // 插入
                    DictUsers users = new DictUsers();
                    users.setUserId(msg.getUserId());
                    users.setPassword(msg.getPassword());
                    users.setDeptCode(msg.getDeptCode());
                    users.setName(msg.getName());
                    users.setAlias(msg.getName());
                    users.setIdentityCard(msg.getIntroduce());
                    users.setJobLevel(msg.getJobLevel());

                    Integer sortNo = 0;
                    if (StringUtils.isNotBlank(msg.getStaffIndexNo())) {
                        sortNo = Integer.valueOf(msg.getStaffIndexNo());
                    }
                    users.setSortNo(String.valueOf(sortNo));
                    dictUsersMapper.insert(users);
                }
            }
        }
    }


    /**
     * 保存 预约信息
     *
     * @param msg
     * @param hospitalCode
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String saveScheduleItem(ChangeExaminationStatusMsg msg, String hospitalCode) {
        ExamApplyDto examApply = new ExamApplyDto();
        examApply.setApplyNo(msg.getELECTR_REQUISITION_NO());

        examApply = examApplyMapper.getExamApply(examApply);
        if (Objects.isNull(examApply)) {
            return "";
        }
        ExamApplyItemDto applyItemQueryDto = new ExamApplyItemDto();
        applyItemQueryDto.setApplyNo(examApply.getApplyNo());
        List<ExamApplyItemDto> applyItemDtos = examApplyItemMapper.getList(applyItemQueryDto);
        examApply.setItems(applyItemDtos);

        if (CollectionUtils.isEmpty(applyItemDtos)) {
            return "";
        }

        QueryWrapper<ExamScheduleItem> scheduleItemQueryWrapper = new QueryWrapper<>();
        scheduleItemQueryWrapper.eq("APPLY_NO", examApply.getApplyNo());
        ExamScheduleItem scheduleItem = examScheduleItemMapper.selectOne(scheduleItemQueryWrapper);

        /**
         * 已存在预约信息直接返回
         */
        if (Objects.nonNull(scheduleItem)) {
//            QueryWrapper<ExamSchedule> scheduleQueryWrapper = new QueryWrapper<>();
//            scheduleQueryWrapper.eq("scheduledId",scheduleItem.getScheduledId());
//            examScheduleMapper.selectOne(scheduleQueryWrapper);
            return scheduleItem.getScheduledId();
        }


//        // 检查类别 根据时间查询预约时段编码和名称
//        QueryWrapper<DictScheduleApm> apmQueryWrapper = new QueryWrapper<>();
//        apmQueryWrapper.eq("examClass", "");
//        apmQueryWrapper.ge("dateStart", "");
//        apmQueryWrapper.le("dateEnd", "");
//        apmQueryWrapper.le("timeEnd", "");
//        apmQueryWrapper.le("timeEnd", "");
//
//        dictScheduleApmMapper.

        // 队列
        String queueName = "无";
        DictExamQueueDto queueDto = new DictExamQueueDto();
        queueDto.setExamClass(examApply.getExamClass());
        queueDto.setHospitalCode(hospitalCode);

        List<DictExamQueueDto> examQueueDtos = dictExamQueueMapper.getQueueList(queueDto);
        if (!CollectionUtils.isEmpty(examQueueDtos)) {
            queueDto = examQueueDtos.get(0);
            queueName = queueDto.getQueueName();
        }

        String status = "08";
        int i = 0;
        int j = 0;
        if (StringUtils.isNotBlank(examApply.getItemCode())) {
            examApply.setActType("0");
        }
        String scheduledId = PKGeneratorSingle.getInstance().nextPKStr();
        List<String> strList = new ArrayList<>();
        for (ExamApplyItemDto item : examApply.getItems()) {
            ExamScheduleItem examScheduleItem = new ExamScheduleItem();
            String no = item.getApplyNo() + item.getItemNo();
            if (strList.contains(no)) {
                continue;
            }
            examScheduleItem.setApplyNo(item.getApplyNo());
            examScheduleItem.setItemNo(item.getItemNo());
            examScheduleItem.setItemName(item.getItemName());
            examScheduleItem.setScheduledId(scheduledId);
            j = examScheduleItemMapper.insert(examScheduleItem);
            strList.add(no);
        }
        ExamSchedule es = new ExamSchedule();
        es.setHospitalCode(hospitalCode);
        es.setApplyNo(examApply.getApplyNo());
        es.setScheduleStatus(status);
        es.setScheduledId(scheduledId);
        es.setApmCode("无");
        es.setQueueName(queueName);
        es.setScheduledDate(examApply.getNewScheduleDate());
        es.setScheduleApm(examApply.getNewScheduleApm());
//        es.setScheduledTime(getScheduleTime(es, ea.getStartTime()));
        es.setHospitalCode(examApply.getHospitalCode());
        es.setScheduler("ADMIN");
        es.setSchePath(ConstantsUtil.TerminalTypeSchePath.getKey(examApply.getTerminalType()));
        es.setEarliestDate(examApply.getEarliestDate());
        es.setEarliestTime(examApply.getEarliestTime());

        String queueClass = (examApply.getPriorityOrder() != null) ? examApply.getPriorityOrder() : "普通";
        es.setQueueClass(queueClass);
        if (Objects.nonNull(examApply.getIsExamClass4Organ()) && examApply.getIsExamClass4Organ()) {
            es.setOrgans(String.valueOf(examApply.getOrgans()));
        } else {
            es.setOrgans("1");
        }
        // 医生排班
        es.setStaffName(null);


        // 队列号码 todo 没有预约时间
//        String queueNoClass = getConfigByName(ConstantsUtil.ConfigName.QUEUE_NO_CLASS.key);
//        if (StringUtils.isNotBlank(queueNoClass)
//                && ConstantsUtil.ScheduleStatus.EIGHT.getStatus().equals(es.getScheduleStatus())
//                && queueNoClass.contains(examApply.getExamClass())) {
//            Map<String, String> param = new HashMap<String, String>();
//            param.put("queueDate", examApply.getNewScheduleDate());
//            param.put("queueName", examApply.getQueueName());
//            param.put("queueApm", examApply.getScheduleApm());
//            param.put("queueClass", queueClass);
//            String queueNo = examScheduleMapper.getScheduleQueueNo(param);
//            es.setQueueNo(queueNo);
//            examApply.setQueueNo(queueNo);
//        }

        i = examScheduleMapper.insert(es);
        if (i == 0 || j == 0) {
            scheduledId = "";
        }
        return scheduledId;
    }


    /**
     * 获取检查项目的队列
     *
     * @param dto
     * @return
     */
    public List<DictExamQueueDto> getQueueList(ExamApplyDto dto) {
        DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
        String hospitalCode = dto.getHospitalCode();
        dictExamQueueDto.setHospitalCode(hospitalCode);
        dictExamQueueDto.setUseFlag("0");
        dictExamQueueDto.setClassAttr(dto.getClassAttr());

        dictExamQueueDto.setExamClass(dto.getExamClass());
        if (StringUtils.isNotBlank(dto.getPerformDept())) {
            dictExamQueueDto.setDeptCode(dto.getPerformDept());
        }
        if (StringUtils.isNotBlank(dto.getIsGreenChannel())) {
            dictExamQueueDto.setQueueName(dto.getQueueName());
            dictExamQueueDto.setUseFlag(null);
            dictExamQueueDto.setDeptCode(null);
        } else if (StringUtils.isNotBlank(dto.getQueueName())) {
            dictExamQueueDto.setQueueName(dto.getQueueName());
        }
        List<DictExamQueueDto> lsQueue = dictExamQueueMapper.getQueueList(dictExamQueueDto);
        return lsQueue;
    }

    /**
     * 获取可用的检查队列
     * 开放预约天数和提前预约天数判断
     *
     * @param queues
     * @param date
     * @param patientSourceDays
     * @return
     */
    public List<DictExamQueueDto> getQueueListByDate(List<DictExamQueueDto> queues, String date, Integer patientSourceDays) {
        List<DictExamQueueDto> list = new ArrayList<DictExamQueueDto>();
        if (queues != null) {
            int queueExpireDays = 0;
            String nowTimeStr = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            for (DictExamQueueDto queue : queues) {
                Integer beginDays = queue.getBeginDays();
                Integer expireDays = queue.getExpireDays();
                if (expireDays == null) {
                    expireDays = patientSourceDays;
                }
                boolean bool = true;
                if (beginDays != null && beginDays != 0) {
                    // String beginDate = DateUtil.addDays((int) beginDays);
                    String beginDate = DateUtils.addDays(nowTimeStr, beginDays);

                    if (date.compareTo(beginDate) < 0) {
                        bool = false;
                    }
                }
                if (bool && expireDays != null) {
                    if (beginDays != null) {
                        expireDays += beginDays;
                        if (queueExpireDays < expireDays) {
                            queueExpireDays = expireDays;
                        }
                    }
                    String expireDate = DateUtils.addDays(nowTimeStr, expireDays - 1);
                    if (date.compareTo(expireDate) > 0) {
                        bool = false;
                    }
                }
                if (bool) {
                    list.add(queue);
                }
            }
        }
        return list;
    }


    /***
     * 获取队列时段
     * @param dictScheduleApmDto
     * @return
     */
    public Map<String, DictScheduleApmDto> getScheduleApmMap(DictScheduleApmDto dictScheduleApmDto) {
        Map<String, DictScheduleApmDto> apmMap = new TreeMap<String, DictScheduleApmDto>();
        List<String> apmCodes = null;
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        List<DictScheduleApmDto> lsApm1 = dictScheduleApmMapper.getDateScheduleApm(dictScheduleApmDto);
        for (DictScheduleApmDto dsa : lsApm1) {
            String key = dsa.getQueueName() + "=" + dsa.getTimeStart() + dsa.getDateStart() + dsa.getDateEnd();
            apmCodes = new ArrayList<String>();
            apmCodes.add(dsa.getApmCode());
            map.put(key, apmCodes);
            if (!"2".equals(dsa.getStopFlag())) {
                apmMap.put(key, dsa);
            }
        }
        List<DictScheduleApmDto> lsApm2 = dictScheduleApmMapper.getWeekScheduleApm(dictScheduleApmDto);
        for (DictScheduleApmDto dsa2 : lsApm2) {
            String key2 = dsa2.getQueueName() + "=" + dsa2.getTimeStart() + dsa2.getDateStart() + dsa2.getDateEnd();
            apmCodes = new ArrayList<String>();
            if (map.containsKey(key2)) {
                apmCodes = map.get(key2);
            }
            apmCodes.add(dsa2.getApmCode());
            map.put(key2, apmCodes);
            if (!apmMap.containsKey(key2) && !"2".equals(dsa2.getStopFlag())) {
                apmMap.put(key2, dsa2);
            }
        }
        List<DictScheduleApmDto> lsApm3 = dictScheduleApmMapper.getCommonScheduleApm(dictScheduleApmDto);
        for (DictScheduleApmDto dsa3 : lsApm3) {
            String key3 = dsa3.getQueueName() + "=" + dsa3.getTimeStart() + dsa3.getDateStart() + dsa3.getDateEnd();
            apmCodes = new ArrayList<String>();
            if (map.containsKey(key3)) {
                apmCodes = map.get(key3);
            }
            apmCodes.add(dsa3.getApmCode());
            map.put(key3, apmCodes);
            if (!apmMap.containsKey(key3) && !"2".equals(dsa3.getStopFlag())) {
                apmMap.put(key3, dsa3);
            }
        }
        Iterator<Map.Entry<String, DictScheduleApmDto>> its = apmMap.entrySet().iterator();
        while (its.hasNext()) {
            Map.Entry obj = its.next();
            DictScheduleApmDto dsa4 = (DictScheduleApmDto) obj.getValue();
            dsa4.setApmCodes(map.get(obj.getKey()));
            if (StringUtils.isBlank(dictScheduleApmDto.getIsGreenChannel()) && "1".equals(dsa4.getStopFlag())) {
                its.remove();
            }
        }
        List<String> apmCodeList = new ArrayList<String>();
        if (StringUtils.isNotBlank(dictScheduleApmDto.getScheduleDate())) {
            Iterator<Map.Entry<String, DictScheduleApmDto>> it = apmMap.entrySet().iterator();
            while (it.hasNext()) {
                DictScheduleApm dsa5 = it.next().getValue();
                if (StringUtils.isBlank(dictScheduleApmDto.getIsGreenChannel())) {
                    if (StringUtils.isNotBlank(dsa5.getTimeScheduleFirst()) && StringUtils.isNotBlank(dsa5.getDaysScheduleFirst()) && !"0".equals(dsa5.getDaysScheduleFirst())) {
                        String scheduleFirst = dictScheduleApmDto.getScheduleDate() + " " + dsa5.getTimeScheduleFirst();
                        Date scheduleFirsttDate = DateUtil.parse(scheduleFirst, "yyyy-MM-dd HH:mm");
                        Date date = new Date();
                        int intervalMin = DateUtils.diffMin(scheduleFirsttDate, date);
                        int firstMin = Integer.parseInt(dsa5.getDaysScheduleFirst()) * 24 * 60;
                        if (intervalMin > firstMin) {
                            it.remove();
                            continue;
                        }
                    }
                    if (StringUtils.isNotBlank(dsa5.getTimeScheduleLatest()) && StringUtils.isNotBlank(dsa5.getDaysScheduleLatest()) && !"0".equals(dsa5.getDaysScheduleLatest())) {
                        String scheduleLatest = dictScheduleApmDto.getScheduleDate() + " " + dsa5.getTimeScheduleLatest();
                        Date scheduleLatestDate = DateUtil.parse(scheduleLatest, "yyyy-MM-dd HH:mm");
                        Date date = new Date();
                        int intervalMin = DateUtils.diffMin(scheduleLatestDate, date);
                        int latestMin = Integer.parseInt(dsa5.getDaysScheduleLatest()) * 24 * 60;
                        if (intervalMin < latestMin) {
                            it.remove();
                            continue;
                        }
                    }
                    if (StringUtils.isNotBlank(dictScheduleApmDto.getCurrTime())) {
                        if (StringUtils.isNotBlank(dsa5.getTimeScheduleFirst()) && (StringUtils.isBlank(dsa5.getDaysScheduleFirst()) || "0".equals(dsa5.getDaysScheduleFirst())) && dictScheduleApmDto.getCurrTime().compareTo(dsa5.getTimeScheduleFirst()) < 0) {
                            it.remove();
                            continue;
                        }
                        if (dsa5.getTimeScheduleLatest() != null && dictScheduleApmDto.getCurrTime().compareTo(dsa5.getTimeScheduleLatest()) > 0) {
                            it.remove();
                            continue;
                        }
                    }
                }
                apmCodeList.add(dsa5.getApmCode());
                if (dsa5.getDateStart() != null && dsa5.getDateEnd() != null) {
                    String paramDate = dictScheduleApmDto.getScheduleDate();
                    if (dsa5.getDateStart().length() == 5) {
                        paramDate = paramDate.substring(5);
                    }
                    if (paramDate.compareTo(dsa5.getDateStart()) >= 0 && paramDate.compareTo(dsa5.getDateEnd()) <= 0) {
                        continue;
                    }
                    if (dsa5.getDateEnd().compareTo(dsa5.getDateStart()) < 0 && paramDate.compareTo(dsa5.getDateStart()) <= 0 && paramDate.compareTo(dsa5.getDateEnd()) <= 0) {
                        continue;
                    }
                    if (dsa5.getDateEnd().compareTo(dsa5.getDateStart()) < 0 && paramDate.compareTo(dsa5.getDateStart()) >= 0 && paramDate.compareTo(dsa5.getDateEnd()) >= 0) {
                        continue;
                    }
                    it.remove();
                }
            }
        }
        if (apmCodeList != null && apmCodeList.size() > 0 && apmMap.size() > 0) {
            Map<String, List> mapRegular = new HashMap<String, List>();
            QueryWrapper<DictScheduleApmRegular> apmRegularQueryWrapper = new QueryWrapper();
            apmRegularQueryWrapper.in("APM_CODE", apmCodeList);
            List<DictScheduleApmRegular> list = dictScheduleApmRegularMapper.selectList(apmRegularQueryWrapper);
            for (DictScheduleApmRegular apmRegular : list) {
                if (mapRegular.containsKey(apmRegular.getApmCode())) {
                    List<String> regularCodeList = mapRegular.get(apmRegular.getApmCode());
                    regularCodeList.add(apmRegular.getRegularId());
                } else {
                    List<String> regularCodeList = new ArrayList<String>();
                    regularCodeList.add(apmRegular.getRegularId());
                    mapRegular.put(apmRegular.getApmCode(), regularCodeList);
                }
            }
            if (mapRegular.size() > 0) {
                for (Map.Entry<String, DictScheduleApmDto> stringDictScheduleApmDtoEntry : apmMap.entrySet()) {
                    DictScheduleApmDto dsa6 = stringDictScheduleApmDtoEntry.getValue();
                    List<String> regularIdList = mapRegular.get(dsa6.getApmCode());
                    dsa6.setRegularIdInfo(regularIdList);
                }
            }
        }
        return apmMap;
    }


    public String getConfigByName(String paramName) {
        if (StringUtils.isBlank(paramName)) {
            return null;
        }
        String paramValue = "";
        DictSysparamsDto dsDto = new DictSysparamsDto();
        dsDto.setParamName(paramName);
        List<DictSysparamsDto> dictSysparamsList = dictSysparamsMapper.selectSysparmsInfoList(dsDto);
        if (dictSysparamsList != null && dictSysparamsList.size() > 0) {
            paramValue = dictSysparamsList.get(0).getParamValue();
            if (StringUtils.isBlank(paramValue)) {
                paramValue = dictSysparamsList.get(0).getDataValue();
            }
        }
        return paramValue;
    }


    public String getScheduleTime(ExamSchedule es, String timeStart) {
        if (StringUtils.isBlank(timeStart)) {
            QueryWrapper<DictScheduleApm> query = new QueryWrapper<>();
            query.eq("APM_CODE", es.getApmCode());

            DictScheduleApm dsa = dictScheduleApmMapper.selectOne(query);
            timeStart = dsa.getTimeStart();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("scheduledDate", es.getScheduledDate());
        map.put("scheduleApm", es.getScheduleApm());
        map.put("queueName", es.getQueueName());

        String scheduleTime = examScheduleMapper.getMaxScheduleTime(map);
        if (StringUtils.isNotBlank(scheduleTime)) {
            scheduleTime = DateUtils.addMinutes(scheduleTime, 1);
        } else {
            scheduleTime = timeStart;
        }
        return scheduleTime;
    }

    public String getRegularId(List<String> regularIdList) {
        StringBuffer sb = new StringBuffer();
        if (regularIdList != null && regularIdList.size() > 0) {
            for (String regularIds : regularIdList) {
                if (StringUtils.isBlank(regularIds)) {
                    continue;
                }
                String[] arr = regularIds.split("=");
                String regularId = "";
                for (int i = 0; i < arr.length; ++i) {
                    if (i == 0 || i == 1 || i == 3 || i == 4) {
                        regularId = regularId + "=" + arr[i];
                    }
                }
                sb.append("-" + regularId.substring(1));
            }
            if (sb.length() > 1) {
                return sb.substring(1);
            }
        }
        return "";
    }

    /**
     * 获取未预约的申请单列表
     */
    public void getNoScheduleApply() {

    }


    /***
     * 推送mq消息和微信消息
     * @param requestVo
     * @return
     */
    public String pushStatusMsg(ChangeExaminationStatusRequestVo2 requestVo) {
        final String dateTimeFormatStr = "yyyy-MM-dd HH:mm:ss";
        try {
            String scheduledDate = "";
            ActTypeConstValue actType = ActTypeConstValue.getByActType(requestVo.getActType());

            logger.info("actType:{},{},{}", actType.getActType(), actType.getStatusCode(), actType.getDescStatus());

            ExamScheduleItemVo scheduleItemVo = null;
            // 预约
            if ("0,1".contains(requestVo.getActType())) {
                scheduledDate = "2022-06-15 18:00～19:00";
                try {
                    scheduleItemVo = examScheduleItemMapper.queryScheduledDate(requestVo.getApplyNo());
                    logger.info("scheduledDate:{}", JSONUtil.toJsonStr(scheduleItemVo));
                    if (Objects.nonNull(scheduleItemVo) && org.springframework.util.StringUtils.hasText(scheduleItemVo.getScheduledDate())
                            && org.springframework.util.StringUtils.hasText(scheduleItemVo.getScheduleApm())) {
                        scheduledDate = scheduleItemVo.getScheduledDate() + " " + scheduleItemVo.getScheduleApm()
                                .replace("～", "-");
                    }
                } catch (Exception e) {
                    logger.error("changeExaminationStatus2", e);
                }
            }
            // 取消预约那些不需要查询预约时间 和 须知


            // 根据申请单号查询开单医生
            QueryWrapper<ExamApply> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("APPLY_NO", "REQ_PHYSICIAN_CODE");
            queryWrapper.eq("APPLY_NO", requestVo.getApplyNo());
            List<ExamApply> examApplies = examApplyMapper.selectList(queryWrapper);
            String applyDrCode = "";
            if (!org.springframework.util.CollectionUtils.isEmpty(examApplies)) {
                applyDrCode = examApplies.get(0).getReqPhysicianCode();
            }

            SendMsg sendMsg = new SendMsg();
            sendMsg.setOPER_STAFF_INDEX_NO(applyDrCode);
            sendMsg.setOPER_DATE(DateUtil.format(new Date(), dateTimeFormatStr));
            sendMsg.setELECTR_REQUISITION_NO(requestVo.getApplyNo());

            if (Objects.nonNull(scheduleItemVo) && org.springframework.util.StringUtils.hasText(scheduleItemVo.getQueueName())) {
                sendMsg.setSCHEDULE_QUEUE_NAME(scheduleItemVo.getQueueName());
            } else {
                sendMsg.setSCHEDULE_QUEUE_NAME(requestVo.getStaffNo());
            }

            sendMsg.setREQUISITION_STATUS(actType.getDescStatus());
            sendMsg.setREQUISITION_STATUS_CODE(actType.getStatusCode());
            sendMsg.setRESERVE_EXAM_DATE(scheduledDate);

            if (Objects.nonNull(scheduleItemVo)
                    && org.springframework.util.StringUtils.hasText(scheduleItemVo.getNotice())) {
                String notice = scheduleItemVo.getNotice();
                if (notice.contains("<notices><notice>")) {
                    NoticeRootDto noticeDto = JacksonUtil.readXmlValue(notice, NoticeRootDto.class);
                    if (Objects.nonNull(noticeDto) && !org.springframework.util.CollectionUtils.isEmpty(noticeDto.getNoticeDto())) {
                        Map<String, String> item = noticeDto.getNoticeDto().get(0);
                        String text = String.valueOf(item.get("text"));
                        if (org.springframework.util.StringUtils.hasText(text)) {
                            text = text.replace("&lt;p&gt;", "")
                                    .replace("&lt;/p&gt;", "")
                                    .replace("&lt;br/&gt;", "")
                                    .replace("<p>", "")
                                    .replace("</p>", "")
                                    .replace("<br/>", "");
                        }
                        String taboo = String.valueOf(item.get("taboo"));
                        if (org.springframework.util.StringUtils.hasText(taboo)) {
                            taboo = taboo.replace("&lt;p&gt;", "")
                                    .replace("&lt;/p&gt;", "")
                                    .replace("&lt;br/&gt;", "")
                                    .replace("<p>", "")
                                    .replace("</p>", "")
                                    .replace("<br/>", "");
                        }

                        // 如果两个都有值 - 相同取其中一个
                        if (org.springframework.util.StringUtils.hasText(taboo) && org.springframework.util.StringUtils.hasText(text)) {
                            if (taboo.equals(text)) {
                                notice = text;
                            } else {
                                notice = taboo + text;
                            }
                        } else {
                            // 取有值的字段
                            if (org.springframework.util.StringUtils.hasText(taboo)) {
                                notice = taboo;
                            } else {
                                notice = text;
                            }
                        }
                    }
                }
                sendMsg.setNOTE(notice);
            } else {
                sendMsg.setNOTE("");
            }

            ChangeExaminationStatusMsg detail = new ChangeExaminationStatusMsg();
            detail.setREQUISITION_STATUS(sendMsg.getREQUISITION_STATUS());
            detail.setNOTE(sendMsg.getNOTE());
            detail.setOPER_DATE(sendMsg.getOPER_DATE());
            detail.setREQUISITION_STATUS_CODE(sendMsg.getREQUISITION_STATUS_CODE());
            detail.setOPER_STAFF_INDEX_NO(sendMsg.getOPER_STAFF_INDEX_NO());
            detail.setSCHEDULE_QUEUE_NAME(sendMsg.getSCHEDULE_QUEUE_NAME());
            detail.setRESERVE_EXAM_DATE(sendMsg.getRESERVE_EXAM_DATE());
            detail.setELECTR_REQUISITION_NO(sendMsg.getELECTR_REQUISITION_NO());

            SendMsgInfo msgInfo = new SendMsgInfo();
            sendMsg.setId(UUID.randomUUID().toString().replace("-", ""));
            sendMsg.setAction("insert");
            sendMsg.setLastUpdate(DateUtil.format(new Date(), dateTimeFormatStr));
            sendMsg.setDetail(Collections.singletonList(detail));
            msgInfo.setMsg(sendMsg);

            MessageHeader header = new MessageHeader();
            header.setFid(paramsConfig.getFid());
            header.setMsgDate(DateUtil.format(new Date(), dateTimeFormatStr));
            header.setOrderNo(paramsConfig.getOrderNo());
            header.setTargetSysCode(paramsConfig.getTargetSysCode());
            header.setSourceSysCode(paramsConfig.getSourceSystemCode());
            header.setReturnFlag(paramsConfig.getReturnFlag());
            header.setHospCode(paramsConfig.getHospCode());

            AccessControl accessControl = new AccessControl();
            accessControl.setFid(paramsConfig.getFid());
            accessControl.setOrderNo(paramsConfig.getOrderNo());
            accessControl.setSysFlag(paramsConfig.getSysFlag());
            accessControl.setUserName(paramsConfig.getUserName());
            accessControl.setPassword(paramsConfig.getPassword());

            SendESBEntry esbEntry = new SendESBEntry();
            esbEntry.setAccessControl(accessControl);
            esbEntry.setMessageHeader(header);
            esbEntry.setMsgInfo(msgInfo);

            String xmlString = JacksonUtil.toXmlString(esbEntry);
            logger.info(xmlString);

            String result = mqClientService.pushMsg(paramsConfig.getChangeExaminationStatusManageMQ(), paramsConfig.getChangeExaminationStatusChannelId(), xmlString);

            //            if ("0,1".contains(requestVo.getActType())) {
//                // 判断预约的项目是否放射科的检查
//                try {
//                    logger.info("开始推送放射科预约消息：{}", JacksonUtil.toJsonString(scheduleItemVo));
//                    xRayService.sendXRayScheduleMsg(scheduleItemVo, requestVo.getApplyNo());
//                } catch (Exception e) {
//                    logger.error("推送放射科预约消息失败:" + e.getMessage(), e);
//                }
//            }

            // 发送微信消息
            if (paramsConfig.getPushWechat()) {
                mqClientService.pushWechatMsg(requestVo);
            }
            return result;
        } catch (Exception e) {
            logger.error("pushStatusMsg:" + JSONUtil.toJsonStr(requestVo), e);
            return "-1:" + e.getMessage();
        }
    }

}
